#!/usr/bin/perl

# This script displays a table of all the calibrators we know about, along with their RA, Dec,
# and the latest flux value we have for them, closest to the recommended frequency in each band.

use CGI qw(:standard);
use DBI;
use POSIX;

use strict; use warnings;

my $buffer;

# read in the parameters
$ENV{'REQUEST_METHOD'}=~tr/a-z/A-Z/;
if ($ENV{'REQUEST_METHOD'} eq "GET"){
    $buffer=$ENV{'QUERY_STRING'};
}
# split information into name/value pairs
my @pairs=split(/\&/,$buffer);
my %FORM;
foreach my $pair (@pairs) {
    my ($name,$value)=split(/\=/,$pair);
    $value=~tr/+/ /;
    $value=~s/%(..)/pack("C",hex($1))/eg;
    $FORM{$name}=$value;
}

print header;
print "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">\n";
print "<link rel=\"stylesheet\" type=\"text/css\" href=\"/stylesheets/ca_style.css\">\n";
print "<title>";
print "Information on ".$FORM{'source'};
print "</title>";
print "<script src=\"/RGraph/libraries/RGraph.common.js\"></script>\n";
print "<script src=\"/RGraph/libraries/RGraph.scatter.js\"></script>\n";

# database details
my $dsn="dbi:Pg:dbname=atca;host=mentok;port=5432";
my $user="postgres";
my $password="";

# Setup the database connection
my $dbh=DBI->connect($dsn,$user,$password,{ RaiseError => 0, AutoCommit => 1});

print "<script>window.onload=function () {\n";

print "var scatter = new RGraph.Scatter('scatter', [\n";

my @get_columns=("fluxdata.data_freq","fluxdata.tripleamp_value",
		 "fluxdata.tripleamp_scatter_measured","observation.time");
my %query_columns;
my $gdt_query_restrictions="observation.id=any(fluxdata.observation_ids) AND fluxdata.frequency=".
    $FORM{'freq'}." AND fluxdata.source='".$FORM{'source'}."'".
    " AND fluxdata.quality_flag=true";
my $gdt_query="SELECT ";
for (my $i=0;$i<=$#get_columns;$i++){
    $query_columns{$get_columns[$i]}=$i;
    if ($i!=0){
	$gdt_query.=",";
    }
    $gdt_query.=$get_columns[$i];
}
$gdt_query.=" FROM fluxdata,observation WHERE ".$gdt_query_restrictions;

my $gdt=$dbh->prepare($gdt_query);
$gdt->execute;

my %datapoints;
while (my @response=$gdt->fetchrow()){
    my @thesefreqs=@{$response[$query_columns{'fluxdata.data_freq'}]};
    my @thesefluxes=@{$response[$query_columns{'fluxdata.tripleamp_value'}]};
    my @theseflux_errors=@{$response[$query_columns{'fluxdata.tripleamp_scatter_measured'}]};
    for (my $i=0;$i<=$#thesefreqs;$i++){
	my $thisfreq1=ceil($thesefreqs[$i]*1000.0);
	my $thisfreq2=floor($thesefreqs[$i]*1000.0);
	if (($thisfreq1==$FORM{'freq'})||($thisfreq2==$FORM{'freq'})){
	    push @{$datapoints{"flux_$thesefreqs[$i]"}},$thesefluxes[$i];
	    push @{$datapoints{"fluxerr_$thesefreqs[$i]"}},$theseflux_errors[$i];
	    push @{$datapoints{"time_$thesefreqs[$i]"}},
	    &time_to_unixtime($response[$query_columns{'observation.time'}]);
	    push @{$datapoints{"ut_$thesefreqs[$i]"}},$response[$query_columns{'observation.time'}];
	    my @allfrequencies;
	    if ($datapoints{'frequencies'}){
		@allfrequencies=@{$datapoints{'frequencies'}};
	    }
	    my $foundfreq=0;
	    for (my $j=0;$j<=$#allfrequencies;$j++){
		if ($thesefreqs[$i]==$allfrequencies[$j]){
		    $foundfreq=1;
		    last;
		}
	    }
	    if ($foundfreq==0){
		push @{$datapoints{'frequencies'}},$thesefreqs[$i];
	    }
	}
    }
}
$gdt->finish;

$dbh->disconnect;

my @allfrequencies;
if ($datapoints{'frequencies'}){
    @allfrequencies=@{$datapoints{'frequencies'}};
}
my ($mintime,$maxtime)=&minmax(@{$datapoints{"time_$allfrequencies[0]"}});
my ($minflux,$maxflux)=&minmax(@{$datapoints{"flux_$allfrequencies[0]"}});

my @fluxes=@{$datapoints{"flux_$allfrequencies[0]"}};
my @fluxerrs=@{$datapoints{"fluxerr_$allfrequencies[0]"}};
my @times=@{$datapoints{"time_$allfrequencies[0]"}};
my @uts=@{$datapoints{"ut_$allfrequencies[0]"}};
for (my $i=0;$i<=$#fluxes;$i++){
    if ($i>0){
	print ",\n";
    }

#    print "[".($times[$i]-$mintime).",".($fluxes[$i]-$minflux).",null,'".$uts[$i].": ".
#	$fluxes[$i]." +/- ".$fluxerrs[$i]."']";
    print "[".($times[$i]).",".($fluxes[$i]).",null,'".$uts[$i].": ".
	$fluxes[$i]." +/- ".$fluxerrs[$i]."']";
}
print "]);\n";

my $timeextra=($maxtime-$mintime)/20.0+600;
$maxtime+=$timeextra;
$mintime-=$timeextra;
my $ntime_labels=4;
my @time_labels;
my $yy=0;
my $timeinterval=($maxtime-$mintime)/(2*$ntime_labels);
for (my $i=0;$i<(2*$ntime_labels);$i++){
    my $thistime=$mintime+$i*$timeinterval;
    if ($yy==1){
	push @time_labels,strftime("%Y-%m-%d %H:%M",localtime($thistime));
	$yy=0;
    } else {
	$yy=1;
    }
}

#$maxtime-=$mintime;
#$mintime-=$mintime;
#$maxflux-=$minflux;
$maxflux+=0.1;
#$minflux-=$minflux;
$minflux-=0.1;
print "scatter.Set('chart.xmax',$maxtime);\n";
print "scatter.Set('chart.xmin',$mintime);\n";
print "scatter.Set('chart.ymax',$maxflux);\n";
print "scatter.Set('chart.ymin',$minflux);\n";
print "scatter.Set('chart.gutter',50);\n";
print "scatter.Set('chart.scale.decimals',3);\n";
print "scatter.Set('chart.text.font','sanserif');\n";
print "scatter.Set('chart.labels', [";
for (my $i=0;$i<=$#time_labels;$i++){
    if ($i!=0){
	print ",";
    }
    print "'".$time_labels[$i]."'";
}
print "]);\n";
print "scatter.Draw();\n";
print "}\n</script>\n";

print "</head><body>\n";

print "<center><h1>Plot of ".$FORM{'source'}." \@ ".$FORM{'freq'}." MHz</h1></center><br />\n";

print "<center><canvas id=\"scatter\" width=\"900\" height=\"300\">[No canvas support]</canvas></center>\n";


print "</body></html>\n";


sub minmax {
    my @array=@_;
    
    my $minval=$array[0];
    my $maxval=$array[0];

    for (my $i=0;$i<=$#array;$i++){
	if ($array[$i]<$minval){
	    $minval=$array[$i];
	}
	if ($array[$i]>$maxval){
	    $maxval=$array[$i];
	}
    }

    return ($minval,$maxval);
}

sub time_to_unixtime {
    my ($ptime)=@_;
    
    $ptime=~/^(\d{4})\-(\d{2})\-(\d{2})\s(\d{2})\:(\d{2})\:(\d{2})/;
    my ($year,$month,$day,$hour,$minute,$second)=($1,$2,$3,$4,$5,$6);
    $year-=1900;
    $month-=1;

    my $utime=mktime($second,$minute,$hour,$day,$month,$year,0,0);

    return $utime;
}
